package cn.senjoeson.triper.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.senjoeson.mylibrary.base.MyBaseAdapter;
import cn.senjoeson.mylibrary.utils.DisplayUtils;
import cn.senjoeson.mylibrary.utilschanged.GlideUtils;
import cn.senjoeson.mylibrary.utilschanged.LogUtils;
import cn.senjoeson.mylibrary.utilschanged.MyToast;
import cn.senjoeson.triper.R;
import cn.senjoeson.triper.activity.DestinationActivity;
import cn.senjoeson.triper.base.GreenDaoManager;
import cn.senjoeson.triper.bean.FavoriteBean;
import cn.senjoeson.triper.bean.FoodDrinkBean;
import cn.senjoeson.triper.bean.PlaceBean;
import cn.senjoeson.triper.bean.Plan;
import cn.senjoeson.triper.dao.FavoriteBeanDao;
import cn.senjoeson.triper.dao.PlaceBeanDao;
import cn.senjoeson.triper.dao.PlanDao;
import cn.senjoeson.triper.utils.DateCalcUtils;
import cn.senjoeson.triper.utils.IdsUtils;

/**
 * Created by senjoeson on 2018/1/7.
 */

public class DinningListAdapter extends RecyclerView.Adapter {


    private List<FoodDrinkBean> mDatas;
    private OnItemClickListener mOnItemClickListener;
    private Context mContext;

    private double[] availableStayTime = {10, 11, 14, 15, 16, 17, 20, 21};
    private double[] avoidAddTime = {9, 12, 13, 14, 18, 19, 20};
    private List<Double> avoidTime = new ArrayList<>();

    public DinningListAdapter(Context mContext) {
        this.mContext = mContext;
    }

    public void setDatas(List<FoodDrinkBean> mDatas) {
        this.mDatas = mDatas;
        // notifyDataSetChanged();
        for (double v : avoidAddTime) {
            avoidTime.add(v);
        }
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.dinninglist_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        ViewHolder viewHolder = (ViewHolder) holder;
        final FoodDrinkBean foodDrinkBean = mDatas.get(position);
        viewHolder.mDinnerName.setText(foodDrinkBean.getDinningName());
        viewHolder.mRatingbar.setRating(foodDrinkBean.getStar());
        // String imageUrl = "http://www.senjoeson.cn/img/backgrounds/timg.jpg";
        GlideUtils.loadImage(viewHolder.itemView.getContext(), foodDrinkBean.getImageUrl(), viewHolder.mDinnerImage);
        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, DestinationActivity.class);
                intent.putExtra("placeId", foodDrinkBean.getFoodrinkId());
                mContext.startActivity(intent);
                /*if (mOnItemClickListener != null) {
                    mOnItemClickListener.onItemClick(v, holder.getAdapterPosition());
                }*/
            }
        });
        viewHolder.mAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*MyToast.showToast("添加到内容地点的列表中,但未指定某个时间,故暂不实现");
                return;*/
                showChangeDialog(foodDrinkBean);
            }
        });
        viewHolder.mLove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FavoriteBeanDao favoriteBeanDao = GreenDaoManager.getInstance().getNewSession().getFavoriteBeanDao();
                List<FavoriteBean> list = favoriteBeanDao.queryBuilder()
                        .where(FavoriteBeanDao.Properties
                                .PlaceId.eq(foodDrinkBean.getFoodrinkId())).build().list();
                if (list != null && list.size() > 0) {
                    MyToast.showToast("Favorite已经存在该地点哦!");
                } else {
                    FavoriteBean favoriteBean = new FavoriteBean();
                    favoriteBean.setFavoriteId(new Random().nextLong());
                    favoriteBean.setPlaceName(foodDrinkBean.getDinningName());
                    favoriteBean.setPlaceId(foodDrinkBean.getFoodrinkId());
                    favoriteBean.setImageUrl(foodDrinkBean.getImageUrl());
                    favoriteBeanDao.insert(favoriteBean);
                    MyToast.showToast("收藏成功!");
                }

            }
        });
    }

    @Override
    public int getItemCount() {
        return mDatas != null ? mDatas.size() : 0;
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.dinnerName)
        TextView mDinnerName;
        @BindView(R.id.ratingbar)
        RatingBar mRatingbar;
        @BindView(R.id.love)
        ImageView mLove;
        @BindView(R.id.add)
        ImageView mAdd;
        @BindView(R.id.dinnerImage)
        ImageView mDinnerImage;

        public ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        if (onItemClickListener != null) {
            this.mOnItemClickListener = onItemClickListener;
        }
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }


    /**
     * 添加到某天
     *
     * @param foodDrinkBean 对应的地点
     */
    private void showChangeDialog(final FoodDrinkBean foodDrinkBean) {

        final Dialog dialog = new Dialog(mContext);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams windowparams = window.getAttributes();
        window.setGravity(Gravity.CENTER);
        Rect rect = new Rect();
        View view1 = window.getDecorView();
        view1.getWindowVisibleDisplayFrame(rect);
        windowparams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        windowparams.width = DisplayUtils.getScreenWidthPixels((Activity) mContext) / 2;

        window.setBackgroundDrawableResource(android.R.color.transparent);
        window.setAttributes(windowparams);

        View view = LayoutInflater.from(mContext).inflate(R.layout.change_day_dialog, null);
        ListView listView = view.findViewById(R.id.listview);


        PlanDao planDao = GreenDaoManager.getInstance().getNewSession().getPlanDao();
        final List<Plan> plans = planDao.queryBuilder().build().list();
        if (plans != null && plans.size() != 0) {
            final ArrayList<String> list1 = new ArrayList<>();
            if (plans.size() > 1) {
                for (int i = 0; i < plans.size(); i++) {
                    list1.add("计划" + (i + 1));
                }
                listView.setAdapter(new MyBaseAdapter<String>(list1) {
                    @SuppressLint("ViewHolder")
                    @Override
                    public View getView(final int position, View convertView, ViewGroup parent) {
                        convertView = LayoutInflater.from(mContext).inflate(R.layout.simple_textview, null);
                        TextView textView = convertView.findViewById(R.id.textview);

                        textView.setText(mDataSets.get(position));
                        textView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Plan plan = plans.get(position);
                                showSetTimeDialog(plan.getPlanId(), position + 1, foodDrinkBean);
                                if (dialog.isShowing()) {
                                    dialog.dismiss();
                                }

                                dialog.dismiss();


                            }
                        });
                        return convertView;
                    }
                });
                dialog.setContentView(view);
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();

            } else if (plans.size() == 1) {

                final long planId = plans.get(0).getPlanId();

                Plan load = GreenDaoManager.getInstance().getNewSession().getPlanDao().load(planId);
                int days = load.getDays();
                ArrayList<String> list = new ArrayList<>();
                for (int i = 0; i < days; i++) {
                    list.add("DAY " + (i + 1));
                }
                listView.setAdapter(new MyBaseAdapter<String>(list) {
                    @SuppressLint("ViewHolder")
                    @Override
                    public View getView(final int position, View convertView, ViewGroup parent) {
                        convertView = LayoutInflater.from(mContext).inflate(R.layout.simple_textview, null);
                        TextView textView = convertView.findViewById(R.id.textview);

                        textView.setText(mDataSets.get(position));
                        textView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                showSetTimeDialog(planId, position + 1, foodDrinkBean);
                                if (dialog.isShowing()) {
                                    dialog.dismiss();
                                }

                            }
                        });
                        return convertView;
                    }
                });
                dialog.setContentView(view);
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();
            }
        } else {
            MyToast.showToast("当前没有任何计划,请先创建一个计划!");


        }


    }



    /**
     * 设置该地点出发时间
     *
     * @param planId
     * @param dayId
     * @param foodDrinkBean
     */
    public void showSetTimeDialog(final long planId, final long dayId, final FoodDrinkBean foodDrinkBean) {
        ArrayList<Double> times = new ArrayList<>();

        //得到所有可有开始的时间.然后查询哪些开始时间已经被占据
        for (double v : availableStayTime) {
            times.add(v);
        }
        //  final double needStayTime = foodDrinkBean.getStayTime();
        final PlaceBeanDao placeBeanDao = GreenDaoManager.getInstance().getNewSession().getPlaceBeanDao();
        //查询这天有多少个地点的开始时间已经存在
        List<PlaceBean> list = placeBeanDao.queryBuilder()
                .where(PlaceBeanDao.Properties.Dayid.eq(dayId))
                .where(PlaceBeanDao.Properties.Planid.eq(planId))
                .build().list();
        for (PlaceBean placeBean : list) {
            double[] doubles = DateCalcUtils.formatTime(placeBean.getTime());
            double stayTime = placeBean.getStayTime();
            if (doubles != null) {    //移除已经存在的开始时间
                for (int i = 0; i < stayTime; i++) {
                    if (times.contains(doubles[0] + i)) {
                        times.remove(doubles[0] + i);
                    }
                }
            }
        }
        for (int i = 0; i < times.size(); i++) {
            if (!judgeSuitTime(times.get(i))) {
                times.remove(i);
            }
        }
        LogUtils.d(times.toString());
        if (times.size() == 0) {
            MyToast.showToast("本日的行程安排已满，建议选择另一天");
            return;
        } else {
            final Dialog dialog = new Dialog(mContext);
            dialog.setTitle("please choose avilable begintime");
            Window window = dialog.getWindow();
            WindowManager.LayoutParams windowparams = null;
            if (window != null) {
                windowparams = window.getAttributes();
                window.setGravity(Gravity.CENTER);
                Rect rect = new Rect();
                View view1 = window.getDecorView();
                view1.getWindowVisibleDisplayFrame(rect);
                windowparams.height = WindowManager.LayoutParams.WRAP_CONTENT;
                windowparams.width = DisplayUtils.getScreenWidthPixels((Activity) mContext) / 2;
                window.setBackgroundDrawableResource(android.R.color.transparent);
                window.setAttributes(windowparams);
            }

            View view = LayoutInflater.from(mContext).inflate(R.layout.change_day_dialog, null);
            ListView listView = view.findViewById(R.id.listview);
            listView.setAdapter(new MyBaseAdapter<Double>(times) {
                @Override
                public View getView(final int position, View convertView, ViewGroup parent) {
                    convertView = LayoutInflater.from(mContext).inflate(R.layout.simple_textview, null);
                    final TextView textView = convertView.findViewById(R.id.textview);
                    String valueOf = String.valueOf(mDataSets.get(position));
                    int indexOf = valueOf.indexOf(".");
                    String substring = valueOf.substring(0, indexOf);
                    textView.setText(substring + ":00");
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            PlaceBean placeBean = new PlaceBean();
                            long foodrinkId = foodDrinkBean.getFoodrinkId();
                            //todo 指定了具体的计划和具体的日期
                           // placeBean.setId(foodrinkId + 1000 * dayId + dayId);//组成部分:fooddrinkid +1000*序列+哪一天
                            placeBean.setId(IdsUtils.setPlaceIds(foodrinkId,planId,dayId));
                            placeBean.setPlanid(planId);
                            placeBean.setDayid(dayId);
                            placeBean.setPlaceName(foodDrinkBean.getDinningName());
                            placeBean.setImageUrl(foodDrinkBean.getImageUrl());
                            placeBean.setFlag(false);
                            placeBean.setStayTime(foodDrinkBean.getStayTime());
                            placeBean.setTime(textView.getText().toString());
                            if (placeBeanDao.load(placeBean.getId()) == null) {
                                placeBeanDao.insert(placeBean);
                                MyToast.showToast("数据添加成功~");
                            } else {
                                MyToast.showToast("数据已被添加,无需重复添加~");
                                LogUtils.d(placeBean.getId() + "");
                            }
                            dialog.dismiss();

                        }
                    });
                    return convertView;
                }
            });
            dialog.setContentView(view);
            dialog.setCanceledOnTouchOutside(true);
            dialog.show();

        }

    }/**/

    /**
     * 判断是否是不适合的时间
     */
    public boolean judgeSuitTime(Double time) {

        if (time >= 9 && time < 10) {       //在九点到十点
            return false;
        } else if (time > 12 && time < 14) {
            return false;
        } else if (time > 18 && time < 20) {
            return false;
        } else if (time > 22) {
            return false;
        } else {
            return true;
        }
    }
}
